import { APP_MODE, Redirect, getInitialData, useAuth } from 'ice';
import store from '@/store';
import { useEffect } from 'react';
import { useMemoizedFn } from 'ahooks';
import { toObj } from './utils/array';
import { jsonMap, sortJSONTree } from './utils/json';

// 鉴权路由，这里根据全局状态中的user信息，更新全局的鉴权配置
export function AuthRouter(props) {
  const SceneConfig = getInitialData().SceneConfig as any[];
  const { location, children } = props;

  const { userInfo } = store.useModelState('user');
  const { setScene } = store.useModelDispatchers('scene');
  const [auth, setAuth] = useAuth();

  const setAuthRef = useMemoizedFn(setAuth);
  const setSceneRef = useMemoizedFn(setScene);

  // 读取用户权限，修改配置 todo （这里整合菜单过滤，排序，进行权限配置）
  useEffect(() => {
    // 后台目录权限配置
    // const menulist = userInfo ? userInfo.menuList || [] : [];
    // 鉴权 Mapper
    // const authMap = toObj(menulist, 'path');

    // 筛选有效的目录 - 并排序
    // const authSceneConfig = jsonMap(
    //   window.SceneConfig,
    //   (item) => ({ ...item }),
    //   (item) => item.path in authMap,
    // );
    // const sortedAuthSceneConfig = sortJSONTree(authSceneConfig, (a, b) => authMap[a.path].sort - authMap[b.path].sort);
    // setSceneRef({ menuList: sortedAuthSceneConfig });

    // 生成权限对象 （ Object<string, any> 类型 ）
    // const newAuth = toObj(menulist, 'path', (item) => item.children || true);
    // setAuthRef(newAuth);

    // 放开鉴权
    setSceneRef({ menuList: window.SceneConfig });
    setAuthRef({});
  }, [setSceneRef, setAuthRef, userInfo, SceneConfig]);

  // 判断是否是登录页
  const isLoginPage = location.pathname === '/login';

  // 未登录
  if (!userInfo) return isLoginPage ? children : <Redirect to="/login" />;

  // 已登录
  return isLoginPage ? <Redirect to="/" /> : children;
}

// 细微权限控制（支持二层嵌套权限，比如 Page : { add: true, remove: true }）
function Auth(props: { children: React.ReactNode; authKey: string; actionKey?: string; fallback?: React.ReactNode }) {
  const { children, authKey, actionKey, fallback } = props;

  const [auth] = useAuth();

  // 判断是否有权限
  const authItem = auth[authKey];

  // 有权限时直接渲染内容
  if (authItem === true || (typeof authItem === 'object' && actionKey && authItem[actionKey])) {
    return children;
  } else {
    // 无权限时显示指定 UI
    return fallback || <></>;
  }
}

export default Auth;
